package utils

import (
	"log"
	"os"
	"time"
)

var (
	logFileName string
	logFile     os.File
)

func RotateFile() {

	if logFileName != "" {
		file, _ := os.Open(logFileName)
		stat, _ := file.Stat()
		fileSize := stat.Size()
		if fileSize > 1*1024*1024 {
			logFile.Close()
			logFileName = ""
		}
	}

	if logFileName == "" {

		logPath := GetRoot() + string(os.PathSeparator) + "logs" + string(os.PathSeparator)
		if _, err := os.Stat(logPath); os.IsNotExist(err) {
			err := os.Mkdir(logPath, os.ModePerm)
			if err != nil {
				log.Fatal("Create Log Path Error:", err)
			}
		}

		logFileName = logPath + time.Now().Format("20060102150405") + ".log"
		logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Fatal(err)
		}
		log.SetOutput(logFile)
	}

}
